package com.wxq.product.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wxq.common.constant.ProductConstant;
import com.wxq.product.dao.AttrAttrgroupRelationDao;
import com.wxq.product.dao.AttrGroupDao;
import com.wxq.product.dao.CategoryDao;
import com.wxq.product.entity.*;
import com.wxq.product.service.CategoryService;
import com.wxq.product.vo.AttrGroupRelationV0;
import com.wxq.product.vo.AttrVo;
import com.wxq.product.dao.AttrAttrgroupRelationDao;
import com.wxq.product.dao.AttrDao;
import com.wxq.product.dao.AttrGroupDao;
import com.wxq.product.dao.CategoryDao;
import com.wxq.product.entity.AttrAttrgroupRelationEntity;
import com.wxq.product.entity.AttrEntity;
import com.wxq.product.entity.AttrGroupEntity;
import com.wxq.product.entity.CategoryEntity;
import com.wxq.product.service.AttrService;
import com.wxq.product.service.CategoryService;
import com.wxq.product.vo.AttrGroupRelationV0;
import com.wxq.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxq.common.utils.PageUtils;
import com.wxq.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @param params
     * @param catelogId
     * @param attrType
     * @return
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", "base".equalsIgnoreCase(attrType)
                        ? ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode()
                        : ProductConstant.attrEnum.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(wapper -> {
                wapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        //从分页对象中获取查询记录集
        List<AttrEntity> recodes = page.getRecords();
        List<AttrVo> attrVoList = recodes.stream().map(attrEntity -> {
            AttrVo attrVo = new AttrVo();
            BeanUtils.copyProperties(attrEntity, attrVo);
            //查询斌设置分组名 groupName，基本属性需要显示分组，销售属性没有属性分组
            if ("base".equalsIgnoreCase(attrType)) {
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrEntity.getAttrId())
                );
                if (relationEntity != null && relationEntity.getAttrGroupId() !=
                        null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            //查询并设置分类名 catelogName
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getAttrId());
            if (categoryEntity != null) {
                attrVo.setCatelogName(categoryEntity.getName());
            }
            return attrVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrVoList);
        return pageUtils;
    }

    /**
     * 保存规格参数
     *
     * @param attrV0
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAttr(AttrVo attrV0) {
        AttrEntity attrEntity = new AttrEntity();
        //保存基本属性
        BeanUtils.copyProperties(attrV0, attrEntity);
        this.save(attrEntity);
        //保存关联关系 - 基本属性
        if (attrV0.getAttrType() ==
                ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attrV0.getAttrGroupId());
            relationDao.insert(relationEntity);
        }

    }
    @Cacheable(value = {"attr"},key = "'attrInfo:'+root.args[0]")
    @Override
    public AttrVo getAttrInfo(Long attrId) {
        AttrVo attrVo = new AttrVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrVo);
        //查询斌设置所属分组信息，只有基本属性才又属性分组
        if (attrVo.getAttrType() ==
                ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                attrVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity =
                        attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        // 查询并设置所属分类信息
        // 一个微服务内部，service之间调用没有问题，考虑到开发便捷性和代码重用
        // 对于是否违背设计原则，高内聚低耦合，本身微服务划分从根本上就已经做到了高内聚低耦合
        Long[] categoryPath = categoryService.findCategoryPath(attrEntity.getCatelogId());
        attrVo.setCatelogPath(categoryPath);
        CategoryEntity categoryEntity =
                categoryDao.selectById(attrEntity.getAttrId());
        if (categoryEntity != null) {
            attrVo.setCatelogName(categoryEntity.getName());
        }
        return attrVo;
    }

    /**
     * 修改规格参数
     * @param attrV0
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAttr(AttrVo attrV0) {
        //修改基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrV0,attrEntity);
        this.updateById(attrEntity);

        //修改分组关联 - 基本属性
        if (attrV0.getAttrType() ==
        ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrV0.getAttrGroupId());
            Long count = relationDao.selectCount(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrV0.getAttrId()));
            if (count > 0){
                //修改关联关系
                relationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id",attrV0.getAttrId()));
            }else {
                //新增关联关系
                relationDao.insert(relationEntity);
            }
        }
    }
    /**
     * 查询属性分组与属性关联关系
     * @param attrgroupId
     * @return 当前属性分组的属性集合
     */
    @Override
    public List<AttrEntity> getAttrRelation(Long attrgroupId) {
        // 从pms_attr_attrgroup表中拆招指定的属性分组
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrgroupId)
        );
        //根据属性分组查找到所有的属性id
        List<Long> attrIds = relationEntities.stream().map(relationEntity->{
            return relationEntity.getAttrId();
        }).collect(Collectors.toList());
        if (attrIds == null || attrIds.size() == 0){
            return null;
        }
        //批量查找所有的属性
        List<AttrEntity> attrEntities = this.listByIds(attrIds);
        return attrEntities;
    }

    /**
     * 删除属性与属性分组关联关系
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationV0[] vos) {
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map(relationV0->{
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(relationV0,relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        relationDao.deleteRelation(entities);

    }

    /**
     * 查询属性分组未关联的属性
     * @param attrgroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long attrgroupId) {
        // 当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        // 当前分组只能关联别的分组没有引用的属性
        // 1. 查找当前分类下的所有属性分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(
                new QueryWrapper<AttrGroupEntity>()
                        .eq("catelog_id", catelogId));
        List<Long> attrGroupIds = attrGroupEntities.stream().map(groupEntity -> {
            return groupEntity.getAttrGroupId();
        }).collect(Collectors.toList());

        // 2. 查找分组关联的所有属性id
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .in("attr_group_id", attrGroupIds));
        List<Long> attrIds = relationEntities.stream().map(relationEntity -> {
            return relationEntity.getAttrId();
        }).collect(Collectors.toList());

        // 3. 从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIds != null && attrIds.size() > 0) {
            queryWrapper.notIn("attr_id", attrIds);
        }

        // 若带有查询条件，则需要拼装查询语句
        String key = (String) params.get("key");
        if (!org.springframework.util.StringUtils.isEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    /**
     * 在指定属性集合里面，查找出能够被检索的属性
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        return baseMapper.selectSearchAttrIds(attrIds);
    }

}